<!--  -->
<template>
  <div class="form">
    <h2 style="text-align: center; margin-top: 30px; margin-bottom: 30px;">我的机构管理</h2>
    <el-form ref="org" :model="org" label-position="top" :rules="rules">
      <!-- <el-form-item label="机构编号">
          <el-input v-model="org.orgId" autocomplete="off" readonly="" />
        </el-form-item> -->

      <el-form-item prop="orgName" label="机构名称">
        <el-input v-model="org.orgName" autocomplete="off" maxlength="50" show-word-limit />
      </el-form-item>
      <el-form-item prop="orgType" label="机构分类">
        <!-- <el-input v-model="org.orgType" autocomplete="off" /> -->
        <el-select v-model="org.orgType" placeholder="请选择">
          <el-option
            v-for="otype in orgT"
            :key="otype.id"
            :value="otype.id"
            :label="otype.typeName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="机构图片">

        <el-upload
          class="avatar-uploader"
          name="files"
          :action="url"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2MB,建议上传360*200的图片</div>
        </el-upload>
        <!-- <img v-if="type==2" :src="org.orgImg" width="200px" height="120px"> -->
      </el-form-item>
      <el-form-item prop="head" label="负责人">
        <!-- <el-input v-model="org.head" autocomplete="off" /> -->
        <el-select v-model="org.head" placeholder="请选择">
          <el-option
            v-for="ohead in head"
            :key="ohead.userId"
            :value="ohead.userId"
            :label="ohead.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="contactTel" label="联系电话(座机)">
        <el-input v-model="org.contactTel" autocomplete="off" type="number" />
      </el-form-item>
      <el-form-item prop="depositBank" label="银行">
        <!-- <el-input v-model="org.depositBank" autocomplete="off" /> -->
        <el-autocomplete
          v-model="org.depositBank"
          class="inline-input"
          :fetch-suggestions="querySearch"
          placeholder="请输入内容"
          :trigger-on-focus="false"
          @select="handleSelect"
        />
      </el-form-item>
      <el-form-item prop="account" label="银行账号">
        <el-input v-model="org.account" autocomplete="off" />
      </el-form-item>
      <el-form-item prop="contacts" label="联系人">
        <el-input v-model="org.contacts" autocomplete="off" />
      </el-form-item>
      <el-form-item prop="contactNumber" label="联系人电话">
        <el-input v-model="org.contactNumber" autocomplete="off" />
      </el-form-item>
      <el-form-item label="地区">
        <!-- <el-input v-model="org.orgAddress" autocomplete="off" /> -->
        <el-cascader
          v-model="selectedOptions"
          size="large"
          :options="options"
          @change="handleChange"
        />
      </el-form-item>

      <el-form-item label="营业时间">
        <el-input v-model="org.orgTime" autocomplete="off" placeholder="例：8:00~20:00" />
      </el-form-item>
      <el-form-item prop="orgEmail" label="机构邮箱">
        <el-input v-model="org.orgEmail" autocomplete="off" />
      </el-form-item>
      <el-form-item prop="shareRatio" label="分账比例">
        <el-input v-model="org.shareRatio" autocomplete="off" />
      </el-form-item>
      <el-form-item label="推荐人">
        <!-- <el-input v-model="org.referenceId" autocomplete="off" /> -->
        <el-select v-model="org.referenceId" placeholder="请选择">
          <el-option
            v-for="oreference in reference"
            :key="oreference.userId"
            :value="oreference.userId"
            :label="oreference.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="推荐人分成">
        <el-input v-model="org.referenceRatio" autocomplete="off" />
      </el-form-item>

    </el-form>
    <div class="buttons">
      <el-button type="primary" @click="handleUpdate('org')">修 改</el-button>
    </div>

  </div>

</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import { getOrgById, getOrgByOrgHead, updateOrg } from '@/api/org'
import { getAll } from '@/api/classType'
import { getConsoleUserById, getUserByGroup, getUserByGroup1 } from '@/api/consoleUser'
import { regionData, CodeToText, TextToCode } from 'element-china-area-data'
export default {
  name: 'MyOrg',
  // import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    var checkphone = (rule, value, callback) => {
    // let phoneReg = /(^1[3|4|5|6|7|8|9]\d{9}$)|(^09\d{8}$)/;
      if (value === '') {
        callback(new Error('请输入手机号'))
      } else if (!this.isCellPhone(value)) { // 引入methods中封装的检查手机格式的方法
        callback(new Error('请输入正确的手机号!'))
      } else {
        callback()
      }
    }
    var checkcard = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入银行卡号'))
      } else if (!this.isCard(value)) { // 引入methods中封装的检查手机格式的方法
        callback(new Error('请输入正确的银行卡号!'))
      } else {
        callback()
      }
    }
    return {
      org: {},
      orgId: '',
      url: process.env.VUE_APP_BASE_API + 'file/',
      imageUrl: '',
      orgT: {},
      options: regionData,
      selectedOptions: [],
      areaList: {},
      area: '',
      banks: [],
      head: [],
      reference: {},
      rules: {
        orgName: [{ required: true, message: '机构名称不能为空', trigger: 'blur' }, { validator: this.validateCharacter, trigger: ['blur', 'change'] }],
        orgType: [{ required: true, message: '机构分类不能为空', trigger: 'blur' }],
        head: [{ required: true, message: '负责人不能为空', trigger: 'blur' }],
        contactTel: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }],
        depositBank: [{ required: true, message: '银行不能为空', trigger: 'blur' }],
        account: [{ required: true, validator: checkcard, trigger: 'blur' }],
        contacts: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
        contactNumber: [{ required: true, validator: checkphone, trigger: 'blur' }],
        orgEmail: [{ required: true, message: '邮箱不能为空', trigger: 'blur' }],
        shareRatio: [{ required: true, message: '分账比例不能为空', trigger: 'blur' }]
      }
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.fetchData()
    this.getOrgType()
    this.getAllReference()
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.banks = this.loadAll()
  },
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {},
  // 方法集合
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = res.obj.split(';')[0]
      this.org.orgImg = this.imageUrl
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const isImage = file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传图片只能是 JPG或PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
      // return true
    },
    fetchData() {
      getOrgByOrgHead().then((resp) => {
        this.orgId = resp.obj.orgId
        getOrgById(this.orgId).then((res) => {
          this.org = res.obj
          this.imageUrl = res.obj.orgImg
          this.area = this.org.orgAddress
          this.jiema()
          this.getAllHead()
          getConsoleUserById(this.org.head).then((resp) => {
            this.head.push(resp.obj)
            console.log(this.head)
          })
        })
      })
    },

    handleUpdate(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.org.orgAddress = this.area
          updateOrg(this.org).then((resp) => {
            this.$notify({
              title: '更新成功',
              type: 'success'
            })
            this.$parent.fetchData()
          })
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },
    getOrgType() {
      getAll().then((resp) => {
        this.orgT = resp.obj
      })
    },
    handleChange(value) {
      console.log(this.selectedOptions)
      this.area = CodeToText[value[0]] + ';' + CodeToText[value[1]] + ';' + CodeToText[value[2]]
      console.log(this.area)
    },
    jiema() {
      console.log(this.area)
      this.areaList = this.area.split(';')
      console.log(this.areaList)
      this.selectedOptions = [TextToCode[this.areaList[0]].code, TextToCode[this.areaList[0]][this.areaList[1]].code, TextToCode[this.areaList[0]][this.areaList[1]][this.areaList[2]].code]
    },
    querySearch(queryString, cb) {
      var banks = this.banks
      var results = queryString ? banks.filter(this.createFilter(queryString)) : banks
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (banks) => {
        return (banks.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    loadAll() {
      return [
        { 'value': '国家开发银行' },
        { 'value': '中国进出口银行' },
        { 'value': '中国农业发展银行' },
        { 'value': '中国银行' },
        { 'value': '中国工商银行' },
        { 'value': '中国建设银行' },
        { 'value': '中国农业银行' },
        { 'value': '光大银行' },
        { 'value': '中国民生银行' },
        { 'value': '中信银行' },
        { 'value': '交通银行' },
        { 'value': '华夏银行' },
        { 'value': '招商银行' },
        { 'value': '兴业银行' },
        { 'value': '广发银行' },
        { 'value': '平安银行' },
        { 'value': '上海浦东发展银行' },
        { 'value': '恒丰银行' },
        { 'value': '浙商银行' },
        { 'value': '渤海银行' },
        { 'value': '中国邮政储蓄银行' },
        { 'value': '城市商业银行' },
        { 'value': '北京银行' },
        { 'value': '天津银行' },
        { 'value': '河北银行' },
        { 'value': '沧州银行' },
        { 'value': '唐山市商业银行' },
        { 'value': '承德银行' },
        { 'value': '张家口市商业银行' },
        { 'value': '秦皇岛银行' },
        { 'value': '邢台银行' },
        { 'value': '廊坊银行' },
        { 'value': '保定银行' },
        { 'value': '邯郸银行' },
        { 'value': '衡水银行' },
        { 'value': '晋商银行' },
        { 'value': '大同市商业银行' },
        { 'value': '长治银行' }

      ]
    },
    handleSelect(item) {
      console.log(item)
      this.org.depositBank = item.value
    },
    getAllHead() {
      getUserByGroup(3).then((resp) => {
        this.head = resp.obj
      })
    },
    getAllReference() {
      getUserByGroup1(2).then((resp) => {
        this.reference = resp.obj
      })
    },
    isCard(val) {
      if (!/^([1-9]{1})(\d{15}|\d{18})$/.test(val)) {
        return false
      } else {
        return true
      }
    },
    isCellPhone(val) {
      if (!/^1[3456789]\d{9}$/.test(val)) {
        return false
      } else {
        return true
      }
    },
    // 特殊字符过滤
    checkSpecificKey(str) {
      var specialKey = "[`~!#$^&*()=|{}':;',\\[\\].<>/?~！#￥……&*（）——|{}【】‘；：”“'。，、？]‘'"
      for (var i = 0; i < str.length; i++) {
        if (specialKey.indexOf(str.substr(i, 1)) !== -1) {
          return false
        }
      }
      return true
    },

    // 验证字符串
    validateFontSize(rule, value, callback) {
      if (value.length < 30) {
        callback()
      } else {
        callback(new Error('字符串长度在1-30之间'))
      }
    },

    // 验证字符串
    validateCharacter(rule, value, callback) {
      if (this.checkSpecificKey(value)) {
        callback()
      } else {
        callback(new Error('请不要输入特殊字符'))
      }
    }

  } // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style  scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 300px;
    height: 200px;
    line-height: 200px;
    text-align: center;
  }
  .avatar {
    width: 300px;
    height: 200px;
    display: block;
  }
  .form{
    border: #E4E7ED 1px solid;
    border-radius: 30px;
    padding: 50px;
    margin: 0 auto;
    width: 900px;
  }
  .buttons{
    text-align: center;
  }

</style>
